package cn.com.sise.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.com.sise.entity.Book;
import cn.com.sise.service.IBookService;
import cn.com.sise.service.impl.BookServiceImpl;

/**
 * Servlet implementation class ShowAllBooksServlet
 */
@WebServlet("/showAllBooksServlet")
public class ShowAllBooksServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		IBookService bookService = new BookServiceImpl();
		List<Book> allBooks = new ArrayList<Book>();
		if (request.getSession().getAttribute("bookList")==null){  //session缓存
			try {
				allBooks = bookService.queryAll();  //所有的数据
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		//添加分页功能  每页显示五条
		// pageNo:jsp页面传来的参数  ，准备跳到第几页
		// currentPage  当前页    totalPage:总页数   total:总条数
		List<Book> books=new ArrayList<>();
		if (request.getAttribute("currentPage")==null){  //第一次访问
			request.setAttribute("currentPage",'1');  //设置当前页为1
		}
		int total = allBooks.size();
		int totalPage=1;
		int currentPage=1;
		int pageNo=1;
		if ((total%5)==0){
			totalPage=(total/5);
		}else {
			totalPage=(total/5)+1;
		}

		if (request.getParameter("pageNo")!=null){
			pageNo =Integer.parseInt(request.getParameter("pageNo"));
			if (pageNo==-1){  //尾页
				currentPage=totalPage;
			}else{
				currentPage=pageNo;
			}
		}
		//设置
		request.setAttribute("totalPage",totalPage);
		request.setAttribute("currentPage",currentPage);
		request.setAttribute("total",total);
		int beginNo=(currentPage-1)*5;
		for (int i=beginNo; i <beginNo+5 ; i++) {
			if (i<total) {  //判断是否越界取数据
				books.add(allBooks.get(i));
			}
		}
		request.getSession().setAttribute("books", books);
		request.getRequestDispatcher("book/bookList.jsp").forward(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
